<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>

      <!-- 放置table组件 -->
      <el-table :data="tableData">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用">
          <template #default="{ row }">
            <span>
              <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
              <span v-else>
                {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }}
              </span>
            </span></template>
        </el-table-column>
        <el-table-column align="center" label="描述">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="onEdit(row)">确定</el-button>
              <el-button size="mini" type="danger" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          layout="prev, pager, next, jumper"
          :current-page="params.page"
          :page-size="params.pagesize"
          :total="total"
          @current-change="changePage"
        />
      </el-row>

      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="closeDialog">
        <!-- 表单内容 -->
        <el-form ref="roleForm" label-width="120px" :model="roleForm" :rules="roleRules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" style="width:300px" size="mini" />
          </el-form-item>

          <el-form-item label="启用">
            <el-switch v-model="roleForm.state" size="mini" />
          </el-form-item>

          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>

          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="onSubmit">确定</el-button>

                <el-button size="mini" @click="closeDialog">取消</el-button>

              </el-col>

            </el-row>

          </el-form-item>

        </el-form>

      </el-dialog>
      <!-- 放置权限弹层 -->
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <!-- 放置权限数据 -->
        <el-tree
          ref="permTree"
          node-key="id"
          :data="permissionData"
          :props="{ label: 'name' }"
          show-checkbox
          default-expand-all
          :default-checked-keys="permIds"
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>

            <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>

          </el-col>

        </el-row>
      </el-dialog>

    </div>

  </div>

</template>

<script>
import { getRoleListAPI, addRoleAPI, updateRoleAPI, delRoleAPI, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transTreeToData } from '@/utils/index'
export default {
  name: 'RoleIndex',
  data() {
    return {
      tableData: [], // 表格数据
      params: { // 请求参数
        page: 1,
        pagesize: 5
      },
      total: 0, // 总条数
      showDialog: false, // 是否显示弹窗
      roleForm: { // 表单数据
        name: '',
        state: false,
        description: ''
      },
      roleRules: { // 表单验证规则
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          {
            // 自定义校验模式
            validator: (rule, value, callback) => {
              if (this.tableData.some(item => item.name === value)) {
                callback(new Error('角色中已经有该名称了'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() { this.getTableData() },
  methods: {
    async getTableData() {
      const res = await getRoleListAPI(this.params)
      this.tableData = res.rows
      this.total = res.total
      this.tableData.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    formatDescription(row) {
      const MAP = {
        0: '已禁用',
        1: '已启用'
      }
      return MAP[row.state]
    },
    changePage(page) {
      this.params.page = page
      this.getTableData()
    },
    onSubmit() {
      this.$refs.roleForm.validate(async(is) => {
        if (is) {
          await addRoleAPI({
            name: this.roleForm.name,
            state: this.roleForm.state ? 1 : 0,
            description: this.roleForm.description
          })
          this.$message.success('提交成功')
          this.getTableData()
          this.closeDialog()
        }
      })
    },
    closeDialog() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    btnEditRow(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async onEdit(row) {
      // 1. 数据校验
      if (!row.editRow.name.trim() || !row.editRow.description.trim()) {
        this.$message.warning('角色名称和描述不能为空~')
        return
      }
      // 2. 调用接口
      await updateRoleAPI({ id: row.id, ...row.editRow })
      this.$message.success('修改角色成功~')
      // 3. 退出编辑
      // row.isEdit = false
      Object.assign(row, {
        isEdit: false,
        ...row.editRow
      })
    },
    async confirmDel(id) {
      await delRoleAPI(id) // 后端删除
      this.$message.success('删除角色成功')
      // 删除的如果是最后一个
      if (this.tableData.length === 1) { this.pageParams.page-- }
      this.getTableData()
    },
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionData = transTreeToData(await getPermissionList(), 0)
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>

